package com.qf.controller.admin;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author wgy
 * @version V1.0
 * @project gp12_xiaomi
 * @package ${PACKAGE_NAME}
 * @description: ${TODO}
 * @date 2022/6/28 9:08
 */
@WebServlet(name = "ImageServlet",urlPatterns = "/goodsImgs/*")
public class ImageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1 如何获取地址
        //URL Uniform Resouces Locator 统一资源定位符 ,绝对路径
        //URI Uniform Resouces Identifier 统一资源标识符 [包括 URL]
        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        String picture = requestURI.substring(requestURI.indexOf("goodsImgs") + 10);
        System.out.println(picture);
        //2 服务器地址文件路径
        String filepath=this.getServletContext().getRealPath("WEB-INF"+ File.separator+"images"+File.separator+picture);
        //3 创建Io流
        File file=new File(filepath);
        if(!file.exists()){
            return;
        }
        FileInputStream fis=new FileInputStream(file);
        byte[] buf=new byte[1024*4];
        int len;
        ServletOutputStream os = response.getOutputStream();
        while((len=fis.read(buf))!=-1){
            os.write(buf,0,len);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
